package czk.concrent.threadSafeCollection.currenthashMap.unsafe;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.IntStream;

/**
 * ConcurrentHashMap线程不安全的验证
 *
 * @Author:ChenZhangKun
 * @Date: 2021/3/25 9:41
 */
public class ConcurrentHashMapUnsafeDemo {
    private static final Logger LOGGER = Logger.getLogger("x");
    /**
     * 定义HashMap
     */
    static Map<String, User> map = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool(10);
        forkJoinPool.execute(() -> {
            IntStream.range(0, 10).mapToObj(i -> new User(i, "czk"))
                    .parallel()
                    .forEach(ConcurrentHashMapUnsafeDemo::register);
        });
        TimeUnit.SECONDS.sleep(1);
    }

    /**
     * 模拟用户注册
     *
     * @param user
     */
    public static void register(User user) {
        if (map.containsKey(user.getName())) {
            LOGGER.info("用户已存在");
        } else {
            map.put(user.getName(), user);
            LOGGER.info("用户注册成功");
        }
    }
}
